const Sequelize = require("sequelize");
module.exports = {
  formatDate(date = new Date(), fmt = "yyyyMMdd") {
    const o = {
      "M+": date.getMonth() + 1,
      "d+": date.getDate(),
      "h+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds(),
      "q+": Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds(),
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
    return fmt;
  },
  formatUser(user) {
    //   return only(user, ['name', 'phone']);
  },

  toInt(str) {
    if (typeof str === "number") return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
  },

  uuid(len = 8) {
    const characters =
      "0123456789ABCDEFGHIJK12134567895LMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyz0123456789";
    let result = "";
    for (let i = 0; i < len; i++) {
      result += characters.charAt(
        Math.floor(Math.random() * characters.length)
      );
    }
    return result;
  },

  filterKey(obj, key) {
    if (!obj) return obj;
    let data = {};
    Object.keys(obj).forEach((item) => {
      if (item !== key) {
        data[item] = obj[item];
      }
    });
    return data;
  },

  getData(data) {
    Object.keys(data).forEach((key) => {
      if (!data[key]) {
        delete data[key];
      }
    });
    return data;
  },

  success(data, message) {
    this.ctx.body = {
      success: true,
      code: 0,
      data,
      message: message || "success",
    };
  },

  error(error, message) {
    const res = {
      success: false,
      code: -1,
    };
    let errorMsg;

    if (error instanceof Error) {
      if (Array.isArray(error.errors)) {
        const errors = error.errors;
        errorMsg = errors[errors.length - 1].message;
      } else {
        errorMsg = error.message;
      }
    } else {
      errorMsg = error;
    }
    const msg = errorMsg || message || "error";
    res.message = msg;
    res.msg = message;
    this.ctx.body = res;
  },

  response(res) {
    if (res instanceof Error) {
      return this.error(error);
    } else {
      return this.success(res);
    }
  },
};
